namespace Cik.Gapi4Net.Core.Json
{
    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;

    internal class CustomArrayCreationConverter<TInterface, T> : JsonConverter
        where T : TInterface
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(TInterface[]).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var list = new List<T>();
            serializer.Populate(reader, list);

            return list.ConvertAll(item => (TInterface)item).ToArray();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotSupportedException();
        }
    }
}